package com.grj.park.boot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.grj.park.boot.domain.Device;
import com.grj.park.boot.domain.R;
import com.grj.park.boot.service.DeviceService;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;

import static cn.hutool.json.JSONUtil.toBean;

@Api(tags = "设备管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/device")
public class DeviceController {

    private final DeviceService deviceService;

    /**
     * 分页查询设备列表
     * @param currentPage 当前页码
     * @param pageSize 每页大小
     * @param during 时间范围
     * @return 分页结果
     */
    @GetMapping("/page")
    @ApiOperation("分页查询设备列表")
    @PreAuthorize("hasAuthority('device:page')")
    public R<Page<Device>> fetchDevicePage(
            @RequestParam int currentPage,
            @RequestParam int pageSize,
            @RequestParam(required = false) String device,
            @RequestParam(required = false) List<LocalDateTime> during
    ) {
        return R.ok(deviceService.fetchDevicePage(currentPage, pageSize, toBean(device, Device.class), during));
    }

    /**
     * 添加设备
     * @param device 设备对象
     * @return 添加结果
     */
    @PostMapping
    @ApiOperation("添加设备")
    @PreAuthorize("hasAuthority('device:post')")
    public R<Void> postDevice(@RequestBody @Valid Device device) {
        deviceService.postDevice(device);
        return R.okMsg("添加设备成功");
    }

    /**
     * 更新设备
     * @param device 设备对象
     * @return 更新结果
     */
    @PutMapping
    @ApiOperation("更新设备")
    @PreAuthorize("hasAuthority('device:put')")
    public R<Void> putDevice(@RequestBody @Valid Device device) {
        deviceService.putDevice(device);
        return R.okMsg("更新设备成功");
    }

    /**
     * 删除设备
     * @param id 设备 ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除设备")
    @PreAuthorize("hasAuthority('device:delete')")
    public R<Void> delDevice(@PathVariable Long id) {
        deviceService.delDevice(id);
        return R.okMsg("删除设备成功");
    }

    /**
     * 批量删除设备
     * @param ids 设备 ID 数组
     * @return 删除结果
     */
    @DeleteMapping("/batch/delete")
    @ApiOperation("批量删除设备")
    @PreAuthorize("hasAuthority('device:batch:delete')")
    public R<Void> batchDelDevice(@RequestParam List<Long> ids) {
        deviceService.batchDelDevice(ids);
        return R.okMsg("批量删除设备成功");
    }

    /**
     * 获取设备详情
     * @param id 设备 ID
     * @return 设备详情
     */
    @GetMapping("/{id}")
    @ApiOperation("获取设备详情")
    @PreAuthorize("hasAuthority('device:get')")
    public R<Device> fetchDeviceById(@PathVariable Long id) {
        return R.ok(deviceService.fetchDeviceById(id));
    }

    /**
     * 导出设备数据
     * @param response 响应对象
     * @throws IOException IO异常
     */
    @GetMapping("/export")
    @ApiOperation("导出设备数据")
    @PreAuthorize("hasAuthority('device:export')")
    public void exportData(HttpServletResponse response) throws IOException {
        List<Device> deviceList = deviceService.list();
        StringBuilder csvContent = new StringBuilder();
        csvContent.append("ID,设备号,设备名称,设备类型,设备版本,IMEI号,SIM号,代理商,设备状态,计费类型,计费标准,激活状态,创建时间\n");
        deviceList.forEach(device -> {
            csvContent.append(device.getId()).append(",")
                    .append(device.getDeviceNumber()).append(",")
                    .append(device.getDeviceName()).append(",")
                    .append("\n");
        });
        String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date()) + ".csv";
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8));
        response.setContentType("application/csv");
        response.getWriter().write(csvContent.toString());
    }

    /**
     * 导入设备数据
     * @param file CSV文件
     * @return 导入结果
     * @throws IOException IO异常
     */
    @PostMapping("/upload")
    @ApiOperation("导入设备数据")
    @PreAuthorize("hasAuthority('device:import')")
    public R<Void> upload(@RequestParam("file") MultipartFile file) throws IOException {
//        List<Device> deviceList = SecurityUtil.parseCsv(file.getInputStream(), Device.class);
//        deviceService.saveBatch(deviceList);
        return R.okMsg("导入设备成功");
    }
}
